<template>
  <div v-loading="loading" class="container">

    <el-form ref="form" :inline="true" label-position="left" size="mini">

      <el-form-item label="Instance:">
        <el-select
          v-model="dbSelectCondition"
          style="min-width: 120px"
          clearable
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in dbSelecteds"
            :key="item.instance"
            :label="item.instance"
            :value="item.instance"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="查询时间:">
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="timestamp"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
          :editable="false"
          @change="timeRangeOnChange"
        />
      </el-form-item>

      <el-form-item label="查询间隔:">
        <el-select
          v-model="timeSelectCondition"
          style="min-width: 80px"
          clearable
          filterable
          placeholder="请选择"
          @change="reloadRefreshTimer"
        >
          <el-option
            v-for="item in timeSelecteds"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="自动刷新:">
        <el-switch
          v-model="autoRefresh"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </el-form-item>

    </el-form>

    <el-card shadow="always">
      <div class="status-card-container">
        <div v-for="(item, index) in osStatus" :key="index" class="status-card">
          <div class="top-card-title">{{ item.label }}</div>
          <div class="top-card-detail">{{ item.value }}</div>
        </div>
      </div>
    </el-card>

    <el-card shadow="always" style="margin-top: 20px">
      <div class="card-header-title" style="display: flex; flex-direction: row; justify-content: space-between; align-items: center">
        <div style="display: flex; flex-direction: row; align-items: flex-end">
          告警诊断
          <el-popover
            v-model="triggerDialogVisible"
            placement="right"
            width="400"
            trigger="manual"
          >
            <el-form ref="triggerForm" :model="triggerForm" label-width="100px" style="margin-top: 20px">
              <el-form-item
                label="告警项："
                prop="target"
                :rules="[{ required: true, message: '告警项不能为空'}]"
              >
                <el-select v-model="triggerForm.target" placeholder="请选择告警项">
                  <el-option
                    v-for="item in triggerOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="small" @click="triggerDialogVisible=false">取消</el-button>
                <el-button type="primary" size="small" @click="onTriggerCommit">确定</el-button>
              </el-form-item>
            </el-form>
            <div slot="reference" style="margin-left: 10px; color: #409EFF; font-size: 14px; cursor:pointer;" @click="triggerDialogVisible=true">
              （手动触发告警）
            </div>
          </el-popover>
        </div>
        <div v-if="alarmHistoaryRecentlyAllData.length > 2" style="font-size: 10px; color: #1890FF;" @click="alarmHistoaryDialogTableVisible=true">查看更多></div>
      </div>
      <el-divider />
      <div class="report-list-container">
        <el-table
          :data="alarmHistoaryRecentlyData"
          style="width: 100%"
          :height="(alarmHistoaryRecentlyData.length > 3 ? 3 : (alarmHistoaryRecentlyData.length === 0 ? 0 : alarmHistoaryRecentlyData.length-1)) * 60 + 110"
        >
          <el-table-column
            prop="level"
            label="等级"
            sortable
            width="80"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.risk_level === '高级'" style="width: 40px; line-height: 20px; background: red; text-align: center; font-size: 10px">
                {{ scope.row.risk_level }}
              </div>
              <div v-if="scope.row.risk_level === '中级'" style="width: 40px; line-height: 20px; background: yellow; text-align: center; font-size: 10px">{{ scope
                .row.risk_level }}
              </div>
              <div
                v-if="scope.row.risk_level === '低级'"
                style="width: 40px; line-height: 20px; background: greenyellow; text-align: center;
                                font-size: 10px"
              >{{ scope.row.risk_level }}
              </div>
            </template>

          </el-table-column>
          <el-table-column
            prop="last_begin_time"
            label="发生时间"
            :formatter="startTimeFormatter"
            sortable
            width="160"
          />
          <el-table-column
            prop="anomaly_type"
            label="异常类型"
          />
          <el-table-column
            prop="description"
            label="异常描述"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="advice"
            label="建议"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="回放"
            width="60"
          >
            <template slot-scope="scope">
              <el-popover
                width="800px"
                placement="left"
                trigger="click"
                @show="playback(scope)"
              >
                <div style="height: 800px;">
                  <lineChart class="detectorDiagnosticChart" :chart-option="detectorDiagnosticChartOption" />
                  <el-divider />
                  <div>
                    <span style="color: #333333; font-weight: bold">该时间段内的CPU进程：</span>
                    <el-table
                      :data="osProgressStateTableData"
                      :span-method="objectSpanMethod"
                      border
                      :height="430"
                      style="width: 100%; margin-top: 5px;"
                    >
                      <el-table-column
                        prop="start_at"
                        label="Time"
                        width="160"
                      />
                      <el-table-column
                        prop="uid"
                        label="uid"
                        width="80"
                      />
                      <el-table-column
                        prop="pid"
                        label="pid"
                        width="80"
                      />
                      <div v-if="osProgressStateType === 'io_saturation'">
                        <el-table-column
                          prop="kB_rd_s"
                          label="kB_rd/s"
                          width="80"
                        />
                        <el-table-column
                          prop="kB_wr_s"
                          label="kB_rd/s"
                          width="80"
                        />
                        <el-table-column
                          prop="kB_ccwr_s"
                          label="kB_ccwr/s"
                          width="80"
                        />
                        <el-table-column
                          prop="iodelay"
                          label="iodelay"
                          width="80"
                        />
                      </div>
                      <div v-else>
                        <el-table-column
                          prop="cpu_rate"
                          label="CPU(%)"
                          width="80"
                        />
                        <el-table-column
                          prop="mem_rate"
                          label="MEM(%)"
                          width="80"
                        />
                      </div>
                      <el-table-column
                        prop="commond"
                        label="Commond"
                      />
                    </el-table>
                  </div>
                </div>
                <div slot="reference" style="width: 30px; height: 30px;">
                  <svg
                    t="1616940117701"
                    class="icon"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="1164"
                    width="30"
                    height="30"
                  >
                    <path
                      d="M277.398 874.572c0 11.78-9.53 21.34-21.34 21.34H128.088c-11.746 0-21.306-9.56-21.306-21.34V618.63c0-11.778 9.56-21.308 21.306-21.308h127.97c11.81 0 21.34 9.532 21.34 21.308v255.942z"
                      fill="#A0D468"
                      p-id="1165"
                    />
                    <path
                      d="M490.694 874.572c0 11.78-9.56 21.34-21.34 21.34h-127.97c-11.778 0-21.338-9.56-21.338-21.34V277.396c0-11.78 9.56-21.338 21.338-21.338h127.97c11.78 0 21.34 9.558 21.34 21.338v597.176z"
                      fill="#4FC2E9"
                      p-id="1166"
                    />
                    <path
                      d="M703.958 874.572c0 11.78-9.53 21.34-21.308 21.34H554.68c-11.78 0-21.34-9.56-21.34-21.34V490.66c0-11.78 9.56-21.306 21.34-21.306h127.968c11.78 0 21.308 9.528 21.308 21.306v383.912z"
                      fill="#48CFAD"
                      p-id="1167"
                    />
                    <path
                      d="M917.252 874.572c0 11.78-9.56 21.34-21.338 21.34h-127.972c-11.778 0-21.306-9.56-21.306-21.34V149.426c0-11.78 9.53-21.338 21.306-21.338h127.972c11.778 0 21.338 9.558 21.338 21.338v725.146z"
                      fill="#5D9CEC"
                      p-id="1168"
                    />
                    <path
                      d="M1002.576 853.266H21.458c-11.78 0-21.34 9.528-21.34 21.306s9.56 21.34 21.34 21.34h981.12c11.78 0 21.306-9.56 21.306-21.34s-9.528-21.306-21.308-21.306z"
                      fill="#434A54"
                      p-id="1169"
                    />
                  </svg>
                </div>
              </el-popover>

            </template>
          </el-table-column>

        </el-table>
      </div>
    </el-card>

    <el-collapse v-model="collapseActiveNames" style="margin-top: 20px">
      <el-collapse-item title="Connections" name="1">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Connections</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="connectionsChartOption" />
          </el-card>
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Client Thread Activity</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="clientThreadActivityChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="Table Locks" name="2">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Query</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="queryChartOption" />
          </el-card>
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Thread Cache</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="threadCacheChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="Temporary Objects" name="3">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Temporary Objects</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="temporaryObjectsCacheChartOption" />
          </el-card>
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Select Types</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="selectTypesChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="Sorts" name="4">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Sorts</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="sortsChartOption" />
          </el-card>
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Slow Queries</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="slowQueriesChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="Aborted" name="5">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Aborted Connections</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="abortedConnectionsChartOption" />
          </el-card>
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Table Locks</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="tableLocksChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="Network" name="6">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Network Traffic</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="networkTrafficChartOption" />
          </el-card>
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Network Usage Hourly（Last 24 hours）</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="networkUsageHourlyChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="Memory" name="7">
        <div class="nineGridContainer">
          <el-card class="nineGrid" style="width: calc(200% + 10px)" shadow="always">
            <div class="card-header-title">MySQL Internal Memory Overview</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="internalMemoryOverviewChartOption" />
          </el-card>
          <!--   占位   -->
          <div />
        </div>
      </el-collapse-item>

      <el-collapse-item title="Command, Handlers, Processes" name="8">
        <div class="nineGridContainer">
          <el-card class="nineGrid" style="width: calc(200% + 10px)" shadow="always">
            <div class="card-header-title">Top Command Counters</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="topCommandCountersChartOption" />
          </el-card>
          <!--   占位   -->
          <div />
          <el-card class="nineGrid" style="width: calc(200% + 10px)" shadow="always">
            <div class="card-header-title">Top Command Counters Hourly（Last 24 hours）</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="topCommandCountersHourlyChartOption" />
          </el-card>
          <!--   占位   -->
          <div />
        </div>
      </el-collapse-item>

      <el-collapse-item title="Query Cache" name="9">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">Query Cache Memory</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="queryCacheMemoryChartOption" />
          </el-card>

          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">Query Cache Activity</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="queryCacheActivityChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="Files and Tables" name="10">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">File Openings</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="fileOpeningsChartOption" />
          </el-card>

          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">Open Files</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="openFilesChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="Table Openings" name="11">
        <div class="nineGridContainer">
          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Table Open Cache Status</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="tableOpenCacheStatusChartOption" />
          </el-card>

          <el-card class="nineGrid" shadow="always">
            <div class="card-header-title">MySQL Open Tables</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="openTablesChartOption" />
          </el-card>
        </div>
      </el-collapse-item>

      <el-collapse-item title="MySQL Table Definition Cache" name="12">
        <div class="nineGridContainer">
          <el-card class="nineGrid" style="width: calc(200% + 10px)" shadow="always">
            <div class="card-header-title">MySQL Table Definition Cache</div>
            <el-divider />
            <lineChart class="mysqlLineChart" :chart-option="tableDefinitionCacheChartOption" />
          </el-card>
          <!--   占位   -->
          <div />
        </div>
      </el-collapse-item>

      <el-backtop />

    </el-collapse>

    <el-dialog title="告警诊断" :visible.sync="alarmHistoaryDialogTableVisible" width="80%">
      <el-table
        :data="alarmHistoaryRecentlyAllData"
        style="width: 100%"
      >
        <el-table-column
          prop="level"
          label="等级"
          sortable
          width="80"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.risk_level === '高级'" style="width: 40px; line-height: 20px; background: red; text-align: center; font-size: 10px">
              {{ scope.row.risk_level }}
            </div>
            <div v-if="scope.row.risk_level === '中级'" style="width: 40px; line-height: 20px; background: yellow; text-align: center; font-size: 10px">{{ scope
              .row.risk_level }}
            </div>
            <div
              v-if="scope.row.risk_level === '低级'"
              style="width: 40px; line-height: 20px; background: greenyellow; text-align: center;
                                font-size: 10px"
            >{{ scope.row.risk_level }}
            </div>
          </template>

        </el-table-column>
        <el-table-column
          prop="last_begin_time"
          label="发生时间"
          :formatter="startTimeFormatter"
          sortable
          width="160"
        />
        <el-table-column
          prop="anomaly_type"
          label="异常类型"
        />
        <el-table-column
          prop="description"
          label="异常描述"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="advice"
          label="建议"
        />
        <el-table-column
          label="回放"
          width="60"
        >
          <template slot-scope="scope">
            <el-popover
              width="800px"
              placement="left"
              trigger="click"
              @show="playback(scope)"
            >
              <div style="height: 800px;">
                <lineChart class="detectorDiagnosticChart" :chart-option="detectorDiagnosticChartOption" />
                <el-divider />
                <div>
                  <span style="color: #333333; font-weight: bold">该时间段内的CPU进程：</span>
                  <el-table
                    v-if="osProgressStateType === 'io_saturation'"
                    :data="osProgressStateTableData"
                    :span-method="objectSpanMethod"
                    border
                    :height="430"
                    style="width: 100%; margin-top: 5px;"
                  >
                    <el-table-column
                      prop="start_at"
                      label="Time"
                      width="160"
                    />
                    <el-table-column
                      prop="uid"
                      label="uid"
                      width="80"
                    />
                    <el-table-column
                      prop="pid"
                      label="pid"
                      width="80"
                    />
                    <el-table-column
                      prop="kB_rd_s"
                      label="kB_rd/s"
                      width="80"
                    />
                    <el-table-column
                      prop="kB_wr_s"
                      label="kB_rd/s"
                      width="80"
                    />
                    <el-table-column
                      prop="kB_ccwr_s"
                      label="kB_ccwr/s"
                      width="80"
                    />
                    <el-table-column
                      prop="iodelay"
                      label="iodelay"
                      width="80"
                    />
                    <el-table-column
                      prop="commond"
                      label="Commond"
                    />
                  </el-table>
                  <el-table
                    v-else
                    :data="osProgressStateTableData"
                    :span-method="objectSpanMethod"
                    border
                    :height="430"
                    style="width: 100%; margin-top: 5px;"
                  >
                    <el-table-column
                      prop="start_at"
                      label="Time"
                      width="160"
                    />
                    <el-table-column
                      prop="uid"
                      label="uid"
                      width="80"
                    />
                    <el-table-column
                      prop="pid"
                      label="pid"
                      width="80"
                    />
                    <el-table-column
                      prop="cpu_rate"
                      label="CPU(%)"
                      width="80"
                    />
                    <el-table-column
                      prop="commond"
                      label="Commond"
                    />
                  </el-table>
                </div>
              </div>
              <div slot="reference" style="width: 30px; height: 30px;">
                <svg t="1616940117701" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1164" width="30" height="30">
                  <path
                    d="M277.398 874.572c0 11.78-9.53 21.34-21.34 21.34H128.088c-11.746 0-21.306-9.56-21.306-21.34V618.63c0-11.778 9.56-21.308 21.306-21.308h127.97c11.81 0 21.34 9.532 21.34 21.308v255.942z"
                    fill="#A0D468"
                    p-id="1165"
                  />
                  <path
                    d="M490.694 874.572c0 11.78-9.56 21.34-21.34 21.34h-127.97c-11.778 0-21.338-9.56-21.338-21.34V277.396c0-11.78 9.56-21.338 21.338-21.338h127.97c11.78 0 21.34 9.558 21.34 21.338v597.176z"
                    fill="#4FC2E9"
                    p-id="1166"
                  />
                  <path
                    d="M703.958 874.572c0 11.78-9.53 21.34-21.308 21.34H554.68c-11.78 0-21.34-9.56-21.34-21.34V490.66c0-11.78 9.56-21.306 21.34-21.306h127.968c11.78 0 21.308 9.528 21.308 21.306v383.912z"
                    fill="#48CFAD"
                    p-id="1167"
                  />
                  <path
                    d="M917.252 874.572c0 11.78-9.56 21.34-21.338 21.34h-127.972c-11.778 0-21.306-9.56-21.306-21.34V149.426c0-11.78 9.53-21.338 21.306-21.338h127.972c11.778 0 21.338 9.558 21.338 21.338v725.146z"
                    fill="#5D9CEC"
                    p-id="1168"
                  />
                  <path
                    d="M1002.576 853.266H21.458c-11.78 0-21.34 9.528-21.34 21.306s9.56 21.34 21.34 21.34h981.12c11.78 0 21.306-9.56 21.306-21.34s-9.528-21.306-21.308-21.306z"
                    fill="#434A54"
                    p-id="1169"
                  />
                </svg>
              </div>
            </el-popover>

          </template>
        </el-table-column>

      </el-table>
      <el-pagination
        class="pagination"
        style="margin-top: 5px"
        background=""
        layout="prev, pager, next"
        :current-page="pageIndex"
        :page-size="pageSize"
        :total="totalItems"
        @current-change="curPageChange"
      />
    </el-dialog>

  </div>
</template>

<script>

import { query, series, query_range } from '../../../api/prometheus'
import { mysqlDetectorAndDiagnostic, mysqlAnomalyTrigger, osProgressStateHistory } from '../../../api/api'
import { formatSeconds, bytesToSize, numConvert, bytesToSizeSecondsRate, stringFoFixed2 } from '../../../utils/index'
import lineChart from '../../../components/echarts/vue-chart'
import { lineChartOption } from '../../../utils/echart-ori-options'
import { pickerOptions } from '../../../utils/date_time_picker_options'
import moment from 'moment'

export default {
  components: { lineChart },
  filters: {
    percentageFilter: function(value) {
      if (!value) {
        return ''
      }
      return Math.round(value * 100) / 100.0 + '%'
    }
  },
  data() {
    return {
      dbSelecteds: [],
      triggerDialogVisible: false,
      triggerForm: {
        target: ''
      },
      triggerOptions: [
        { label: 'cpu_saturation', value: '0' },
        { label: 'io_saturation', value: '1' },
        { label: 'database_backup', value: '2' },
        { label: 'table_restore', value: '3' },
        { label: 'poorly_physical_design', value: '4' },
        { label: 'poorly_written_query', value: '5' },
        { label: 'workload_spike', value: '6' },
        { label: 'network_congestion', value: '7' },
        { label: 'lock_contention', value: '8' },
        { label: 'vacuum_analyze', value: '9' }
      ],
      dbSelectCondition: undefined,
      collapseActiveNames: ['1'],
      timeSelecteds: [
        { label: '5s', value: '5s' },
        { label: '10s', value: '10s' },
        { label: '30s', value: '30s' },
        { label: '1m', value: '1m' },
        { label: '2m', value: '2m' },
        { label: '3m', value: '3m' },
        { label: '5m', value: '5m' },
        { label: '10m', value: '10m' },
        { label: '30m', value: '30m' }
      ],
      timeSelectedToMs: {
        '5s': 5000,
        '10s': 10000,
        '30s': 30000,
        '1m': 60000,
        '2m': 120000,
        '3m': 180000,
        '5m': 300000,
        '10m': 6000000,
        '30m': 18000000
      },
      pageSize: 8,
      pageIndex: 1,
      totalItems: 0,
      refreshTimer: undefined,
      timeSelectCondition: '2m',
      pickerOptions: pickerOptions,
      timeRange: [],
      alarmHistoaryRecentlyData: [],
      alarmHistoaryRecentlyAllData: [],
      alarmHistoaryDialogTableVisible: false,
      osStatus: [
        { label: '运行时间', value: '' },
        { label: 'Current QPS', value: '' },
        { label: 'Current Connections', value: '' },
        { label: 'Query Cache Size', value: '' },
        { label: 'Open Tables', value: '' },
        { label: 'Table Open Cache', value: '' },
        { label: 'InnoDB Buffer Pool Size', value: '' },
        { label: 'Buffer Pool Size of Total RAM', value: '' },
        { label: 'Key Buffer Size', value: '' }
      ],
      loading: false,
      autoRefresh: false,
      osProgressStateTableData: [],
      osProgressStateType: '',
      connectionsChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      clientThreadActivityChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      queryChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      threadCacheChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      temporaryObjectsCacheChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      selectTypesChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      sortsChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      slowQueriesChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      abortedConnectionsChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      tableLocksChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      networkTrafficChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      networkUsageHourlyChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      internalMemoryOverviewChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      topCommandCountersChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      topCommandCountersHourlyChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      queryCacheMemoryChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      queryCacheActivityChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      fileOpeningsChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      openFilesChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      tableOpenCacheStatusChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      openTablesChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      tableDefinitionCacheChartOption: JSON.parse(JSON.stringify(lineChartOption)),
      detectorDiagnosticChartOption: JSON.parse(JSON.stringify(lineChartOption))
    }
  },
  watch: {
    dbSelectCondition(value) {
      this.reloadRequest()
    },
    timeSelectCondition(value) {
      this.reloadRequest()
    }
  },
  mounted() {
    this.timeRange = [moment().add(-1, 'h').format('x'), moment().format('x')]

    //  MySQL Connections
    this.connectionsChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.connectionsChartOption.xAxis.type = 'time'
    this.connectionsChartOption.color = ['#1890FF', '#00FFFF', '#FFFF00']
    this.connectionsChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.connectionsChartOption.legend.data = ['Max Used Connections', 'Max Connections', 'Connections']
    this.connectionsChartOption.series = [
      {
        name: 'Max Used Connections',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Max Connections',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Connections',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    //  MySQL Client Thread Activity
    this.clientThreadActivityChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.clientThreadActivityChartOption.xAxis.type = 'time'
    this.clientThreadActivityChartOption.color = ['#975FE4', '#01DF3A', '#1890FF']
    this.clientThreadActivityChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.clientThreadActivityChartOption.legend.data = ['Max Used Connections', 'Max Connections', 'Connections']
    this.clientThreadActivityChartOption.series = [
      {
        name: 'Max Used Connections',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Max Connections',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Connections',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    //  MySQL Questions
    this.queryChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.queryChartOption.xAxis.type = 'time'
    this.queryChartOption.color = ['#1890FF']
    this.queryChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.queryChartOption.legend.data = ['Questions']
    this.queryChartOption.series = [
      {
        name: 'Questions',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false
      }
    ]

    // MySQL Thread Cache
    this.threadCacheChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.threadCacheChartOption.xAxis.type = 'time'
    this.threadCacheChartOption.color = ['#01DF3A', '#FFFF00', '#1890FF']
    this.threadCacheChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.threadCacheChartOption.legend.data = ['Thread Cache Size', 'Threads Cached', 'Threads Created']
    this.threadCacheChartOption.series = [
      {
        name: 'Thread Cache Size',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Threads Cached',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Threads Created',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL Temporary Objects
    this.temporaryObjectsCacheChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.temporaryObjectsCacheChartOption.xAxis.type = 'time'
    this.temporaryObjectsCacheChartOption.color = ['#FE2E2E', '#00FFFF', '#1890FF']
    this.temporaryObjectsCacheChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.temporaryObjectsCacheChartOption.legend.data = ['Created Tmp Tables', 'Created Tmp Disk Tables', 'Created Tmp Files']
    this.temporaryObjectsCacheChartOption.series = [
      {
        name: 'Created Tmp Tables',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Created Tmp Disk Tables',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Created Tmp Files',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL Select Types
    this.selectTypesChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.selectTypesChartOption.xAxis.type = 'time'
    this.selectTypesChartOption.color = ['#00FFFF', '#1890FF']
    this.selectTypesChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.selectTypesChartOption.legend.data = ['Select Scan', 'Select Full Join']
    this.selectTypesChartOption.series = [
      {
        name: 'Select Scan',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Select Full Join',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL Sorts
    this.sortsChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.sortsChartOption.xAxis.type = 'time'
    this.sortsChartOption.color = ['#1890FF', '#FE2E2E']
    this.sortsChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.sortsChartOption.legend.data = ['Sort Scan', 'Sort Rows', 'Sort Merge Passes', 'Sort Range']
    this.sortsChartOption.series = [
      {
        name: 'Sort Scan',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Sort Rows',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Sort Merge Passes',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Sort Range',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL Slow Queries
    this.slowQueriesChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.slowQueriesChartOption.xAxis.type = 'time'
    this.slowQueriesChartOption.color = ['#01DF3A']
    this.slowQueriesChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.slowQueriesChartOption.legend.data = ['Slow Queries']
    this.slowQueriesChartOption.series = [
      {
        name: 'Slow Queries',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL Aborted Connections
    this.abortedConnectionsChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.abortedConnectionsChartOption.xAxis.type = 'time'
    this.abortedConnectionsChartOption.color = ['#CC2EFA', '#1890FF']
    this.abortedConnectionsChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.abortedConnectionsChartOption.legend.data = ['Aborted Clients (timeout)', 'Aborted Connects (attempts)']
    this.abortedConnectionsChartOption.series = [
      {
        name: 'Aborted Clients (timeout)',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Aborted Connects (attempts)',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL Table Locks
    this.tableLocksChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.tableLocksChartOption.xAxis.type = 'time'
    this.tableLocksChartOption.color = ['#FF8000', '#FE2EF7']
    this.tableLocksChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.tableLocksChartOption.legend.data = ['Table Locks Immediate', 'Table Locks Waited']
    this.tableLocksChartOption.series = [
      {
        name: 'Table Locks Immediate',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Table Locks Waited',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL Network Traffic
    this.networkTrafficChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${bytesToSizeSecondsRate(param.value[1]).replace('-', '')}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.networkTrafficChartOption.xAxis.type = 'time'
    this.networkTrafficChartOption.grid.left = 60
    this.networkTrafficChartOption.color = ['#01DF3A', '#FE2EF7']
    this.networkTrafficChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.networkTrafficChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return bytesToSizeSecondsRate(value)
    }
    this.networkTrafficChartOption.legend.data = ['Inbound', 'Outbound']
    this.networkTrafficChartOption.series = [
      {
        name: 'Inbound',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Outbound',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL Network Usage Hourly
    this.networkUsageHourlyChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${bytesToSizeSecondsRate(param.value[1]).replace('-', '')}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.networkUsageHourlyChartOption.xAxis.type = 'time'
    this.networkUsageHourlyChartOption.grid.left = 60
    this.networkUsageHourlyChartOption.color = ['#01DF3A', '#FE2E2E']
    this.networkUsageHourlyChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.networkUsageHourlyChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return bytesToSizeSecondsRate(value)
    }
    this.networkUsageHourlyChartOption.legend.data = ['Received', 'Sent']
    this.networkUsageHourlyChartOption.series = [
      {
        name: 'Received',
        data: [],
        type: 'bar'
      },
      {
        name: 'Sent',
        data: [],
        type: 'bar'
      }
    ]

    //  MySQL Internal Memory Overview
    this.internalMemoryOverviewChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${bytesToSize(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.internalMemoryOverviewChartOption.xAxis.type = 'time'
    this.internalMemoryOverviewChartOption.grid.left = 60
    this.internalMemoryOverviewChartOption.grid.right = 160
    this.internalMemoryOverviewChartOption.legend = {
      icon: 'pin',
      padding: 5,
      itemWidth: 10,
      itemHeight: 5,
      itemGap: 10,
      right: 0,
      top: '30',
      orient: 'vertical',
      textStyle: {
        fontSize: 12
      }
    }
    // this.internalMemoryOverviewChartOption.color = ['#FE2E2E', '#1890FF', '#FF8000', '#01DF3A', '#FFFF00', '#FE2EF7', '#58ACFA', '#6A0888']
    this.internalMemoryOverviewChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.internalMemoryOverviewChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return bytesToSize(value)
    }
    this.internalMemoryOverviewChartOption.legend.data = ['InnoDB Log Buffer Size', 'Key Buffer Size', 'InnoDB Buffer Pool Data', 'Query Cache Size']
    this.internalMemoryOverviewChartOption.series = [
      {
        name: 'InnoDB Log Buffer Size',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Key Buffer Size',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'InnoDB Buffer Pool Data',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Query Cache Size',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    //  Top Command Counters
    this.topCommandCountersChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${bytesToSize(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.topCommandCountersChartOption.xAxis.type = 'time'
    this.topCommandCountersChartOption.grid.left = 60
    this.topCommandCountersChartOption.grid.right = 160
    // this.topCommandCountersChartOption.color = ['#FE2E2E', '#1890FF', '#FF8000', '#01DF3A', '#FFFF00', '#FE2EF7', '#58ACFA', '#6A0888']
    this.topCommandCountersChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.topCommandCountersChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return bytesToSize(value)
    }
    this.topCommandCountersChartOption.legend.data = ['Com_set_option', 'Com_change_db', 'Com_select', 'Com_commit', 'Com_insert', 'Com_update',
      'Com_delete', 'Com_replace', 'Com_insert_select', 'Com_show_variables', 'Com_show_status', 'Com_show_variables', 'Com_admin_commands']
    this.topCommandCountersChartOption.series = [
      {
        name: 'Com_set_option',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_change_db',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_select',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_commit',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_insert',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_update',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_delete',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_replace',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_insert_select',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_show_variables',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_show_status',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_show_variables',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Com_admin_commands',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]
    this.topCommandCountersChartOption.legend = {
      type: 'scroll',
      icon: 'pin',
      padding: 5,
      itemWidth: 10,
      itemHeight: 5,
      itemGap: 10,
      right: 0,
      top: '0',
      orient: 'vertical',
      textStyle: {
        fontSize: 12
      }
    }

    //  Top Command Counters Hourly
    this.topCommandCountersHourlyChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${bytesToSize(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.topCommandCountersHourlyChartOption.xAxis.type = 'time'
    this.topCommandCountersHourlyChartOption.grid.left = 60
    this.topCommandCountersHourlyChartOption.grid.right = 160
    this.topCommandCountersHourlyChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.topCommandCountersHourlyChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return bytesToSize(value)
    }
    this.topCommandCountersHourlyChartOption.legend.data = ['Com_set_option', 'Com_change_db', 'Com_select', 'Com_commit', 'Com_insert', 'Com_update',
      'Com_delete', 'Com_replace', 'Com_insert_select', 'Com_show_variables', 'Com_show_status', 'Com_show_variables', 'Com_admin_commands']
    this.topCommandCountersHourlyChartOption.series = [
      {
        name: 'Com_set_option',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_change_db',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_select',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_commit',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_insert',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_update',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_delete',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_replace',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_insert_select',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_show_variables',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_show_status',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_show_variables',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      },
      {
        name: 'Com_admin_commands',
        data: [],
        type: 'bar',
        stack: 'topCommandCountersHourly'
      }
    ]
    this.topCommandCountersHourlyChartOption.legend = {
      type: 'scroll',
      icon: 'pin',
      padding: 5,
      itemWidth: 10,
      itemHeight: 5,
      itemGap: 10,
      right: 0,
      top: '0',
      orient: 'vertical',
      textStyle: {
        fontSize: 12
      }
    }

    // MySQL Query Cache Memory
    this.queryCacheMemoryChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${bytesToSize(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.queryCacheMemoryChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return bytesToSize(value)
    }
    this.queryCacheMemoryChartOption.xAxis.type = 'time'
    this.queryCacheMemoryChartOption.grid.left = 60
    this.queryCacheMemoryChartOption.color = ['#01DF3A']
    this.queryCacheMemoryChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.queryCacheMemoryChartOption.legend.data = ['Query Cache Size', 'Free Memory']
    this.queryCacheMemoryChartOption.series = [
      {
        name: 'Query Cache Size',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Free Memory',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL Query Cache Activity
    this.queryCacheActivityChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${stringFoFixed2(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.queryCacheActivityChartOption.xAxis.type = 'time'
    this.queryCacheActivityChartOption.color = ['#FF8000']
    this.queryCacheActivityChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.queryCacheActivityChartOption.legend.data = ['Not Cached', 'Queries in Cache', 'Prunes', 'Inserts', 'Hits']
    this.queryCacheActivityChartOption.series = [
      {
        name: 'Not Cached',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Queries in Cache',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Prunes',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Inserts',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Hits',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL File Openings
    this.fileOpeningsChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${numConvert(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.fileOpeningsChartOption.xAxis.type = 'time'
    this.fileOpeningsChartOption.color = ['#B40404']
    this.fileOpeningsChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.fileOpeningsChartOption.legend.data = ['Openings']
    this.fileOpeningsChartOption.series = [
      {
        name: 'Openings',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]
    this.fileOpeningsChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return numConvert(value)
    }

    // Open Files
    this.openFilesChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${numConvert(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.openFilesChartOption.xAxis.type = 'time'
    this.openFilesChartOption.color = ['#8A4B08']
    this.openFilesChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return numConvert(value)
    }
    this.openFilesChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.openFilesChartOption.legend.data = ['Open Files', 'Open Files Limit', 'InnoDB Open Files']
    this.openFilesChartOption.series = [
      {
        name: 'Open Files',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Open Files Limit',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'InnoDB Open Files',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]

    // MySQL Table Open Cache Status
    this.tableOpenCacheStatusChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${numConvert(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.tableOpenCacheStatusChartOption.xAxis.type = 'time'
    this.tableOpenCacheStatusChartOption.color = ['#FAAC58']
    this.tableOpenCacheStatusChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.tableOpenCacheStatusChartOption.legend.data = ['Hits', 'Table Open Cache Hit Ratio', 'Misses', 'Openings']
    this.tableOpenCacheStatusChartOption.series = [
      {
        name: 'Hits',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Table Open Cache Hit Ratio',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Misses',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Openings',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]
    this.tableOpenCacheStatusChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return numConvert(value)
    }

    // MySQL Open Tables
    this.openTablesChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${numConvert(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.openTablesChartOption.xAxis.type = 'time'
    this.openTablesChartOption.color = ['#01DF3A']
    this.openTablesChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.openTablesChartOption.legend.data = ['Table Open Cache', 'Open Tables']
    this.openTablesChartOption.series = [
      {
        name: 'Table Open Cache',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Open Tables',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      }
    ]
    this.openTablesChartOption.yAxis.axisLabel.formatter = function(value, index) {
      return numConvert(value)
    }

    // MySQL Table Definition Cache
    this.tableDefinitionCacheChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}:&nbsp ${numConvert(param.value[1])}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.tableDefinitionCacheChartOption.xAxis.type = 'time'
    this.tableDefinitionCacheChartOption.grid.right = 40
    this.tableDefinitionCacheChartOption.color = ['#FF0080']
    this.tableDefinitionCacheChartOption.yAxis = [{
      type: 'value',
      offset: 0,
      nameTextStyle: {
        color: '#666666'
      },
      axisLabel: {
        show: true,
        showMinLabel: true,
        fontSize: 10,
        formatter: function(value, index) {
          return numConvert(value)
        }
      },
      axisLine: {
        show: false
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#e5e5e5',
          type: 'dotted'
        }
      },
      axisTick: {
        show: false
      }
    }, {
      type: 'value',
      offset: 0,
      nameTextStyle: {
        color: '#666666'
      },
      axisLabel: {
        show: true,
        showMinLabel: true,
        fontSize: 10
      },
      axisLine: {
        show: false
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#e5e5e5',
          type: 'dotted'
        }
      },
      axisTick: {
        show: false
      }
    }]
    this.tableDefinitionCacheChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'
    this.tableDefinitionCacheChartOption.legend.data = ['Table Definitions Cache Size', 'Open Table Definitions', 'Opened Table Definitions(right-y)']
    this.tableDefinitionCacheChartOption.series = [
      {
        name: 'Table Definitions Cache Size',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Open Table Definitions',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: { type: 'default' }
      },
      {
        name: 'Opened Table Definitions(right-y)',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        yAxisIndex: 1,
        areaStyle: { type: 'default' }
      }
    ]

    // detectorDiagnostic
    this.detectorDiagnosticChartOption.tooltip.formatter = function(params, ticket, callback) {
      var result = params[0].axisValueLabel + '</br>'
      for (let i = 0; i < params.length; i++) {
        const param = params[i]
        result = result + `${param.marker}&nbsp${param.seriesName}(${param.value[2]}):&nbsp ${param.value[1]}</br>`
      }
      setTimeout(function() {
        // 仅为了模拟异步回调
        callback(ticket, result)
      }, 100)
      return 'loading...'
    }
    this.detectorDiagnosticChartOption.xAxis.type = 'time'
    this.detectorDiagnosticChartOption.grid.left = 60
    this.detectorDiagnosticChartOption.grid.top = 30
    this.detectorDiagnosticChartOption.grid.bottom = 50
    this.detectorDiagnosticChartOption.xAxis.axisLabel.formatter = '{HH}:{mm}'

    this.nodesInfo()
  },
  beforeDestroy() {
    this.clearRefreshTimer()
  },
  methods: {
    onTriggerCommit() {
      this.triggerDialogVisible = false
      mysqlAnomalyTrigger({ target: this.triggerForm.target }).then(res => {
        this.$message.success('任务已经添加，请等待')
      })
    },
    startTimeFormatter(row, column) {
      return moment(row.last_begin_time).format('YYYY-MM-DD HH:mm:ss')
    },
    timeRangeOnChange() {
      if (this.timeRange && this.timeRange.length > 1) {
        this.reloadRequest()
      }
    },
    playback(scope) {
      const list = JSON.parse(scope.row.anomaly_metrics_list)
      this.detectorDiagnosticChartOption.series = []
      this.detectorDiagnosticChartOption.legend.data = []
      for (let i = 0; i < list.length; i++) {
        this.detectorDiagnosticChartOption.legend.data.push(list[i].name)
        const data = list[i].data
        for (let j = 0; j < data.length; j++) {
          const item = data[j]
          item[0] = moment(item[0]).format('YYYY-MM-DD HH:mm:ss')
          item[1] = stringFoFixed2(item[1])
          item[2] = list[i].name_value
        }
        this.detectorDiagnosticChartOption.series.push(
          {
            name: list[i].name,
            data: data,
            type: 'line',
            smooth: true,
            showSymbol: false,
            areaStyle: { type: 'default' }
          }
        )
      }
      this.osProgressStateType = scope.row.anomaly_type
      console.log(scope.row)
      this.getOsProgressStateHistory(scope.row.last_begin_time)
    },
    getOsProgressStateHistory(start_at) {
      osProgressStateHistory({
        instance: this.dbSelectCondition,
        start_at: moment(start_at).add(-1, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
        end_at: moment(start_at).add(1, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
        sort_type: this.osProgressStateType === 'io_saturation' ? this.osProgressStateType : 'cpu_saturation'
      }).then(res => {
        this.osProgressStateTableData = []
        const data = res.data
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          const list = JSON.parse(item['history_json'])
          for (let j = 0; j < Math.min(list.length, 5); j++) {
            var progress = list[j]
            progress['start_at'] = item['start_at']
            console.log(progress['start_at'])
            this.osProgressStateTableData.push(progress)
          }
        }
      })
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex % 5 === 0) {
          return {
            rowspan: 5,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    reloadRefreshTimer() {
      this.clearRefreshTimer()
      this.refreshTimer = setInterval(() => {
        if (this.autoRefresh) {
          this.timeRange = [moment().add(-1, 'h').format('x'), moment().format('x')]
          this.reloadRequest()
        }
      }, this.timeSelectedToMs[this.timeSelectCondition])
    },
    clearRefreshTimer() {
      clearInterval(this.refreshTimer)
      this.refreshTimer = null
    },
    nodesInfo() {
      series({ 'match[]': 'mysql_up', start: parseInt((new Date()).valueOf() / 1000) - 1000, end: parseInt((new Date()).valueOf() / 1000) }).then(res => {
        this.dbSelecteds = res.data.data
        this.dbSelectCondition = this.dbSelecteds[0].instance
      })
    },
    reloadRequest() {
      if (!this.dbSelectCondition) {
        return
      }

      this.mysqlDetectorAndDiagnostic()

      this.queryRequest(`mysql_global_status_uptime{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.osStatus[0].value = res ? formatSeconds(res) : 'No Data'
      })

      this.queryRequest(`rate(mysql_global_status_queries{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_queries{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.osStatus[1].value = res ? stringFoFixed2(res) : 'No Data'
      })

      this.queryRequest(`max(max_over_time(mysql_global_status_threads_connected{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])  or mysql_global_status_threads_connected{instance="${this.dbSelectCondition}"} )`).then(res => {
        this.osStatus[2].value = res || 'No Data'
      })

      this.queryRequest(`mysql_global_variables_query_cache_size{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.osStatus[3].value = res ? bytesToSize(res) : 'No Data'
      })

      this.queryRequest(`mysql_global_variables_table_open_cache{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.osStatus[4].value = res ? bytesToSize(res) : 'No Data'
      })

      this.queryRequest(`mysql_global_status_open_tables{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.osStatus[5].value = res ? stringFoFixed2(res) : 'No Data'
      })

      this.queryRequest(`mysql_global_variables_innodb_buffer_pool_size{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.osStatus[6].value = res ? bytesToSize(res) : 'No Data'
      })

      this.queryRequest(`(mysql_global_variables_innodb_buffer_pool_size{instance="${this.dbSelectCondition}"} * 100) / on (instance) node_memory_MemTotal_bytes{instance="${this.dbSelectCondition}"}`).then(res => {
        this.osStatus[7].value = res ? bytesToSize(res) : 'No Data'
      })

      this.queryRequest(`mysql_global_variables_key_buffer_size{instance=~"${this.dbSelectCondition}"}`).then(res => {
        this.osStatus[8].value = res ? bytesToSize(res) : 'No Data'
      })

      this.queryRangeRequest(`mysql_global_status_max_used_connections{instance="${this.dbSelectCondition}"}`).then(res => {
        this.connectionsChartOption.series[0].data = res
      })

      this.queryRangeRequest(`mysql_global_variables_max_connections{instance="${this.dbSelectCondition}"}`).then(res => {
        this.connectionsChartOption.series[1].data = res
      })

      this.queryRangeRequest(`max(max_over_time(mysql_global_status_threads_connected{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])  or mysql_global_status_threads_connected{instance="${this.dbSelectCondition}"} )`).then(res => {
        this.connectionsChartOption.series[2].data = res
      })

      this.queryRangeRequest(`max_over_time(mysql_global_status_threads_connected{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or max_over_time(mysql_global_status_threads_connected{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.clientThreadActivityChartOption.series[0].data = res
      })

      this.queryRangeRequest(`max_over_time(mysql_global_status_threads_running{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or max_over_time(mysql_global_status_threads_running{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.clientThreadActivityChartOption.series[1].data = res
      })

      this.queryRangeRequest(`avg_over_time(mysql_global_status_threads_running{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or avg_over_time(mysql_global_status_threads_running{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.clientThreadActivityChartOption.series[2].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_questions{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_questions{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.queryChartOption.series[0].data = res
      })

      this.queryRangeRequest(`mysql_global_variables_thread_cache_size{instance="${this.dbSelectCondition}"}`).then(res => {
        this.threadCacheChartOption.series[0].data = res
      })

      this.queryRangeRequest(`mysql_global_status_threads_cached{instance="${this.dbSelectCondition}"}`).then(res => {
        this.threadCacheChartOption.series[1].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_threads_created{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_threads_created{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.threadCacheChartOption.series[2].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_created_tmp_tables{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_created_tmp_tables{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.temporaryObjectsCacheChartOption.series[0].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_created_tmp_disk_tables{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_created_tmp_disk_tables{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.temporaryObjectsCacheChartOption.series[1].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_created_tmp_files{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_created_tmp_files{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.temporaryObjectsCacheChartOption.series[2].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_select_scan{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_select_scan{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.selectTypesChartOption.series[0].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_select_full_join{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_select_full_join{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.selectTypesChartOption.series[1].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_sort_rows{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_sort_rows{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.sortsChartOption.series[0].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_sort_scan{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_sort_scan{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.sortsChartOption.series[1].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_sort_range{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_sort_range{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.sortsChartOption.series[2].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_sort_merge_passes{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_sort_merge_passes{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.sortsChartOption.series[3].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_slow_queries{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_slow_queries{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.slowQueriesChartOption.series[0].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_aborted_clients{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_aborted_clients{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.abortedConnectionsChartOption.series[0].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_aborted_connects{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_aborted_connects{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.abortedConnectionsChartOption.series[1].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_table_locks_immediate{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_table_locks_immediate{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.tableLocksChartOption.series[0].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_table_locks_waited{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_table_locks_waited{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.tableLocksChartOption.series[1].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_bytes_received{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_bytes_received{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.networkTrafficChartOption.series[0].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_bytes_sent{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_bytes_sent{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`, true).then(res => {
        res = res.data.data.result[0].values
        var results = []
        for (let i = 0; i < res.length; i++) {
          const value = res[i]
          results.push([value[0] * 1000, -value[1]])
        }
        this.networkTrafficChartOption.series[1].data = results
      })

      this.queryRangeRequest(`increase(mysql_global_status_bytes_received{instance="${this.dbSelectCondition}"}[1h])`).then(res => {
        this.networkUsageHourlyChartOption.series[0].data = res
      })

      this.queryRangeRequest(`increase(mysql_global_status_bytes_sent{instance="${this.dbSelectCondition}"}[1h])`, true).then(res => {
        res = res.data.data.result[0].values
        var results = []
        for (let i = 0; i < res.length; i++) {
          const value = res[i]
          results.push([value[0] * 1000, -value[1]])
        }
        this.networkUsageHourlyChartOption.series[1].data = results
      })

      this.queryRangeRequest(`mysql_global_variables_innodb_log_buffer_size{instance="${this.dbSelectCondition}"}`).then(res => {
        this.internalMemoryOverviewChartOption.series[0].data = res
      })

      this.queryRangeRequest(`mysql_global_variables_key_buffer_size{instance="${this.dbSelectCondition}"}`).then(res => {
        this.internalMemoryOverviewChartOption.series[1].data = res
      })

      this.queryRangeRequest(`mysql_global_status_innodb_page_size{instance="${this.dbSelectCondition}"} * on (instance) mysql_global_status_buffer_pool_pages{instance="${this.dbSelectCondition}",state="data"}`).then(res => {
        this.internalMemoryOverviewChartOption.series[2].data = res
      })

      this.queryRangeRequest(`mysql_global_variables_query_cache_size{instance="${this.dbSelectCondition}"}`).then(res => {
        this.internalMemoryOverviewChartOption.series[3].data = res
      })

      this.queryRangeRequest(`topk(5, rate(mysql_global_status_commands_total{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])>0) or topk(5, irate(mysql_global_status_commands_total{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])>0)`, true).then(res => {
        const dataIndexList = ['set_option', 'change_db', 'select', 'commit', 'insert', 'update', 'delete', 'replace', 'insert_select', 'show_variables', 'show_status',
          'show_variables', 'admin_commands']
        res = res.data.data.result
        for (let i = 0; i < res.length; i++) {
          const value = res[i]
          const metric = value.metric
          const values = value.values
          var results = []
          for (let i = 0; i < values.length; i++) {
            const item = values[i]
            results.push([item[0] * 1000, item[1]])
          }
          if (dataIndexList.indexOf(metric.command) >= 0) {
            this.topCommandCountersChartOption.series[dataIndexList.indexOf(metric.command)].data = results
          }
        }
      })

      this.queryRangeRequest(`topk(5, increase(mysql_global_status_commands_total{instance="${this.dbSelectCondition}"}[1h])>0)`, true).then(res => {
        const dataIndexList = ['set_option', 'change_db', 'select', 'commit', 'insert', 'update', 'delete', 'replace', 'insert_select', 'show_variables', 'show_status',
          'show_variables', 'admin_commands']
        res = res.data.data.result
        for (let i = 0; i < res.length; i++) {
          const value = res[i]
          const metric = value.metric
          const values = value.values
          var results = []
          for (let i = 0; i < values.length; i++) {
            const item = values[i]
            results.push([item[0] * 1000, item[1]])
          }
          if (dataIndexList.indexOf(metric.command) >= 0) {
            this.topCommandCountersHourlyChartOption.series[dataIndexList.indexOf(metric.command)].data = results
          }
        }
      })

      this.queryRangeRequest(`mysql_global_variables_query_cache_size{instance="${this.dbSelectCondition}"}`).then(res => {
        this.queryCacheMemoryChartOption.series[0].data = res
      })

      this.queryRangeRequest(`mysql_global_status_qcache_free_memory{instance="${this.dbSelectCondition}"}`).then(res => {
        this.queryCacheMemoryChartOption.series[1].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_qcache_not_cached{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_qcache_not_cached{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.queryCacheActivityChartOption.series[0].data = res
      })

      this.queryRangeRequest(`mysql_global_status_qcache_queries_in_cache{instance="${this.dbSelectCondition}"}`).then(res => {
        this.queryCacheActivityChartOption.series[1].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_qcache_lowmem_prunes{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_qcache_lowmem_prunes{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.queryCacheActivityChartOption.series[2].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_qcache_inserts{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_qcache_inserts{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.queryCacheActivityChartOption.series[3].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_qcache_hits{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_qcache_hits{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.queryCacheActivityChartOption.series[4].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_opened_files{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_opened_files{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.fileOpeningsChartOption.series[0].data = res
      })

      this.queryRangeRequest(`mysql_global_status_open_files{instance="${this.dbSelectCondition}"}`).then(res => {
        this.openFilesChartOption.series[0].data = res
      })

      this.queryRangeRequest(`mysql_global_variables_open_files_limit{instance="${this.dbSelectCondition}"}`).then(res => {
        this.openFilesChartOption.series[1].data = res
      })

      this.queryRangeRequest(`mysql_global_status_innodb_num_open_files{instance="${this.dbSelectCondition}"}`).then(res => {
        this.openFilesChartOption.series[2].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_table_open_cache_hits{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_table_open_cache_hits{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.tableOpenCacheStatusChartOption.series[0].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_table_open_cache_overflows{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_opened_files{mysql_global_status_table_open_cache_overflows="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.tableOpenCacheStatusChartOption.series[1].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_table_open_cache_misses{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_table_open_cache_misses{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.tableOpenCacheStatusChartOption.series[2].data = res
      })

      this.queryRangeRequest(`rate(mysql_global_status_opened_tables{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_opened_tables{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.tableOpenCacheStatusChartOption.series[3].data = res
      })

      this.queryRangeRequest(`mysql_global_variables_table_open_cache{instance="${this.dbSelectCondition}"}`).then(res => {
        this.openTablesChartOption.series[0].data = res
      })

      this.queryRangeRequest(`mysql_global_status_open_tables{instance="${this.dbSelectCondition}"}`).then(res => {
        this.openTablesChartOption.series[1].data = res
      })

      this.queryRangeRequest(`mysql_global_variables_table_definition_cache{instance="${this.dbSelectCondition}"}`).then(res => {
        this.tableDefinitionCacheChartOption.series[0].data = res
      })
      this.queryRangeRequest(`mysql_global_status_open_table_definitions{instance="${this.dbSelectCondition}"}`).then(res => {
        this.tableDefinitionCacheChartOption.series[1].data = res
      })
      this.queryRangeRequest(`rate(mysql_global_status_opened_table_definitions{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}]) or irate(mysql_global_status_opened_table_definitions{instance="${this.dbSelectCondition}"}[${this.timeSelectCondition}])`).then(res => {
        this.tableDefinitionCacheChartOption.series[2].data = res
      })
    },
    queryRequest(queryUrl) {
      return new Promise((resolve, reject) => {
        query({ query: queryUrl }).then(res => {
          const data = res.data.data
          if (data && data.result && data.result.length > 0 && data.result[0].value) {
            resolve(data.result[0].value[1])
          } else {
            resolve(undefined)
          }
        })
      })
    },
    queryRangeRequest(queryUrl, original = false) {
      return new Promise((resolve, reject) => {
        query_range({
          query: queryUrl,
          start: this.timeRange[0] ? this.timeRange[0] / 1000 : (new Date()).valueOf() / 1000 - 3600 * 24,
          end: this.timeRange[1] ? this.timeRange[1] / 1000 : (new Date()).valueOf() / 1000,
          step: parseInt(this.timeSelectedToMs[this.timeSelectCondition]) / 1000
        }).then(res => {
          const data = res.data.data
          if (data && data.result && data.result.length > 0) {
            if (original) {
              resolve(res)
            } else {
              if (data.result[0].values.length > 0) {
                const values = data.result[0].values
                var results = []
                for (let i = 0; i < values.length; i++) {
                  const value = values[i]
                  results.push([value[0] * 1000, value[1]])
                }
                resolve(results)
              } else {
                resolve(undefined)
              }
            }
          } else {
            resolve(undefined)
          }
        })
      })
    },
    mysqlDetectorAndDiagnostic() {
      mysqlDetectorAndDiagnostic({ instance: this.dbSelectCondition, page: this.pageIndex, page_size: this.pageSize }).then((res) => {
        if (res.data) {
          this.totalItems = res.count
          this.alarmHistoaryRecentlyAllData = JSON.parse(JSON.stringify(res.data))
          this.alarmHistoaryRecentlyData = res.data.splice(0, 2)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    gotoMonitoringServer() {
      this.$router.push({
        path: '/monitoring_server'
      })
    },
    async curPageChange(page) {
      this.pageIndex = page
      this.mysqlDetectorAndDiagnostic()
    }
  }
}
</script>

<style scoped>
  .container >>> .el-collapse-item__header {
    background: #f9f9f9;
  }
</style>

<style lang="scss" scoped>

  .container {
    display: flex;
    flex-direction: column;
    width: 100%;
  }

  .status-card-container {
    margin: auto;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    overflow-x: auto;
  }

  .status-card {
    min-width: 80px;
    margin-right: 10px;
    display: flex;
    min-height: 50px;
    flex-direction: column;
    justify-content: flex-start;
  }

  .top-card-title {
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
    text-align: center;
    height: 20px;
  }

  .top-card-detail {
    color: rgba(0, 0, 0, 0.85);
    font-weight: bolder;
    font-size: 18px;
    margin-top: 5px;
    text-align: center;
  }

  .card-header-title {
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    white-space: nowrap;
    word-break: break-all;
    font-size: 18px;
  }

  .el-divider--horizontal {
    margin: 20px 0;
  }

  .el-col-5 {
    width: 20%;
  }

  .nineGridContainer {
    display: grid;
    grid-template-columns: repeat(2, 1fr); /* 相当于 1fr 1fr 1fr */
    grid-gap: 10px; /* grid-column-gap 和 grid-row-gap的简写 */
    grid-auto-flow: row;

    .nineGrid {
      background-color: #FFFFFF;
    }

    margin-top: 20px;
  }

  .mysqlLineChart {
    width: 100%;
    height: 200px;
  }

  .detectorDiagnosticChart {
    width: 800px;
    height: 300px;
  }

</style>
